
//
//  UserViewController.m
//  Lovely Food
//
//  Created by 李经纬 on 15/11/27.
//  Copyright © 2015年 李经纬. All rights reserved.
//

#import "UserViewController.h"
#import "UserView.h"
#import "LoginViewController.h"
#import <AVOSCloud.h>
#import "AllocationViewController.h"
#import "UIImageView+WebCache.h"
#import "CacheFileManager.h"
#import "UserTableViewCell.h"
#import "FlickrTableViewController.h"

@interface UserViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UserView *myView;

@property (nonatomic, strong) UIButton *loginButton;

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    self.navigationItem.title = @"用户";
    
    // 创建tableView
    self.view.backgroundColor = [UIColor blueColor];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
//    self.tableView.scrollEnabled = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dataArray = [NSMutableArray arrayWithCapacity:10];
    
    NSArray *arrayOne = @[@"个人配置", @"我的晒照", @"我的收藏", @"我的关注", @"我的草稿"];
    NSArray *arrayTwo = @[@"反馈中心", @"清除缓存", @"推荐我们"];
    self.dataArray = @[arrayOne, arrayTwo].mutableCopy;
    
    NSLog(@"%@",self.dataArray);
    
    UINib *nib = [UINib nibWithNibName:@"UserTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"UserCell"];
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
     [self.navigationController setNavigationBarHidden:YES animated:nil];
    // 当用户为空的时候按钮进行变化
    AVUser *currentUser = [AVUser currentUser];

    if (currentUser != nil) {
        self.loginButton.selected = YES;
    } else {
        self.loginButton.selected = NO;
    }
    [self.tableView reloadData];
}

#pragma TableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserCell" forIndexPath:indexPath];

    cell.titleLabel.text = self.dataArray[indexPath.section][indexPath.row];
    if (indexPath.section == 1 && indexPath.row == 1) {
      NSString *str =[ NSString stringWithFormat:@"缓存大小 : %0.2fM", [CacheFileManager folderSizeAtPath:[CacheFileManager CachesDirectory]]];
        cell.accessoryLabel.text = str;
    }
    
    
    return cell;
}

// 设置头视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 200;
    } else {
        return 0.1;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}
// 设置尾视图的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return 100;
    } else {
        return 5;
    }
}
// 添加头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        // 创建TopView
        UIView *topView = [[UIView alloc] init];
        topView.frame = CGRectMake(0, 0, self.view.frame.size.width, 160);
        topView.backgroundColor = [UIColor clearColor];
        self.myView = [[UserView alloc] init];
        self.myView.topImageView.frame = CGRectMake(self.view.frame.size.width / 2 - 60, 40, 120, 120);
        self.myView.topImageView.layer.cornerRadius = 60;
        if ([AVUser currentUser] == nil) {
            
            self.myView.topImageView.image = [UIImage imageNamed:@"touxiang"];
            
        } else {
            
            AVFile *imageFile = [[AVUser currentUser] objectForKey:@"headImage"];
            [self.myView.topImageView sd_setImageWithURL:[NSURL URLWithString:imageFile.url] placeholderImage:[UIImage imageNamed:@"touxiang"]];
        }
        
        
        
        self.myView.frame = CGRectMake(0, 0, self.view.frame.size.width, 195);
        
        
        self.myView.backgroundImageView.frame = self.myView.frame;
        
        self.myView.numberLabel.frame = CGRectMake(self.myView.frame.size.width - 100, self.myView.frame.size.height - 40, 60, 20);
        
        [topView addSubview:self.myView];
        return topView;
    }
    return nil;
    
}

// 添加尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        view.frame = CGRectMake(0, 0, 100, 100);
        
        //  创建登陆按钮
        self.loginButton= [UIButton buttonWithType:(UIButtonTypeCustom)];
        self.loginButton.backgroundColor = [UIColor redColor];
        self.loginButton.frame = CGRectMake(self.view.frame.size.width / 2 - 40, view.frame.size.height / 2 - 20, 80, 40);
        [self.loginButton setTitle:@"登陆" forState:(UIControlStateNormal)];
        [self.loginButton setTitle:@"退出" forState:(UIControlStateSelected)];
        self.loginButton.layer.borderColor = [[UIColor whiteColor] CGColor];
        self.loginButton.layer.borderWidth = 1;
        self.loginButton.layer.masksToBounds = YES;
        self.loginButton.layer.cornerRadius = 15;

        
        
        // 当用户为空的时候按钮进行变化
        AVUser *currentUser = [AVUser currentUser];

        if (currentUser != nil) {
            self.loginButton.selected = YES;
        } else {
            self.loginButton.selected = NO;
        }
        
        [self.loginButton addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [view addSubview:self.loginButton];
        
        return view;
    }
    
    return nil;
}

// 登陆按钮事件
- (void)buttonAction:(UIButton *)button
{
    
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser != nil) {
        
        UIAlertController *logOutAlert = [UIAlertController alertControllerWithTitle:@"退出账号" message:@"退出当前账号" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *OKButton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
             [AVUser logOut];
            [self.tableView reloadData];

        }];
        [logOutAlert addAction:cancel];
        [logOutAlert addAction:OKButton];
        self.loginButton.selected = NO;
        // 删除本地存储
        NSUserDefaults *myUser = [NSUserDefaults standardUserDefaults];
        [myUser removeObjectForKey:@"userName"];
        [myUser removeObjectForKey:@"userId"];
        [myUser synchronize];
        
        
        [self presentViewController:logOutAlert animated:YES completion:^{
            
        }];
        
        
    } else {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        
        [self presentViewController:loginVC animated:YES completion:^{
            
        }];

    }

    

}

// 选择cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([AVUser currentUser] != nil) {
        // 登录状态下
        if (indexPath.row == 0 && indexPath.section == 0) {
            // 个人设置
            AllocationViewController *allocation = [[AllocationViewController alloc] initWithStyle:(UITableViewStyleGrouped)];
            
            [self.navigationController pushViewController:allocation animated:YES];
        } else if (indexPath.row == 1 && indexPath.section == 0) {
            // 我的相册
            FlickrTableViewController *flickr = [[FlickrTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
            
            [self showViewController:flickr sender:nil];
        }
        
    } else if ([AVUser currentUser] == nil && indexPath.section != 1) {
        // 没有登录的状态下
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请先登录" message:@"登陆后进行操作" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *OKbutton = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:OKbutton];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
        
    }
    
    if (indexPath.section == 1 && indexPath.row == 1) {
        
            
            [CacheFileManager clearCache:[CacheFileManager CachesDirectory]];
            [self.tableView reloadData];
                
            
           
       }
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
